package com.fengxu.gamescript.util

import android.animation.ValueAnimator
import androidx.core.animation.doOnEnd

/**
 * 多个动画同时开启的操作工具类
 */
class MultiAnimUtils {

    // 动画的个数
    var size = 0
        get() = anims.size
        private set

    // 动画数组
    private var anims:MutableList<ValueAnimator> = mutableListOf()

    // 动画状态数组
    private lateinit var animStates:MutableList<Boolean>

    //是否正在运行
    var running:Boolean = false

    // 所有动画全部完成事件
    var allEndEvent:(()->Unit)? = null

    constructor(){
        animStates = mutableListOf()
    }

    constructor(vararg animator: ValueAnimator){
       anims.addAll(animator)
        animStates = MutableList(size){false}
    }

    constructor(anim:Collection<ValueAnimator>){
        this.anims.addAll(anim)
        animStates = MutableList(size){false}
    }

    /**
     * 添加一个动画
     */
    fun addAnim(anim: ValueAnimator){
        anims.add(anim)
        animStates.add(false)
    }

    /**
     * 开始动画
     */
    fun start(){
        running = true
        for ((index, anim) in anims.withIndex()) {
            anim.start()
            anim.doOnEnd {
                animStates[index] = true
                if(animStates.all { it }){
                    running = false
                    allEndEvent?.invoke()
                }
            }
        }
    }

}